/*
 * Copyright (c) 2018, dreamkaylee@foxmail.com All Rights Reserved.
 */

package com.common.interceptor;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.springframework.util.StringUtils;

/**
 * 日期格式化绑定
 * @author limk
 * @date 2018年2月12日 下午9:14:23
 * @version 1.0
 */
public class DateConvertEditor extends PropertyEditorSupport {
	
	private final String SEPARATOR = ":";
	private int date = 10;
	private int second = 19;
	private int millisecond = 21;
	
	private SimpleDateFormat datetimeFormat = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (StringUtils.hasText(text)) {
			try {
				if (text.indexOf(SEPARATOR) == -1 && text.length() == date) {
					setValue(this.dateFormat.parse(text));
				} else if (text.indexOf(SEPARATOR) > 0 && text.length() == second) {
					setValue(this.datetimeFormat.parse(text));
				} else if (text.indexOf(SEPARATOR) > 0 && text.length() == millisecond) {
					text = text.replace(".0", "");
					setValue(this.datetimeFormat.parse(text));
				} else {
					throw new IllegalArgumentException(
							"Could not parse date, date format is error ");
				}
			} catch (ParseException ex) {
				IllegalArgumentException iae = new IllegalArgumentException(
						"Could not parse date: " + ex.getMessage());
				iae.initCause(ex);
				throw iae;
			}
		} else {
			setValue(null);
		}
	}
}
